<template>
  <div class="title">Watch & Computed</div>
  <div class="inner">
    <div>
        <span>金额1：&nbsp;<b>{{numAccount1}}</b></span>
        <span>{{changeStr1}}</span>
        <span>金额2：&nbsp;<b>{{numAccount2}}</b></span>
        <span>{{changeStr2}}</span>
    </div>
    <div>
        <span>合计：&nbsp;<b>{{totalNum}}</b></span>
    </div>
    <div>
       <label for="">
        <span>输入变化值</span>
       <input type="text" v-model="strAmountDiff1">
       <input type="text" v-model="strAmountDiff2">
       <button @click="changeNum">点击</button>
    </label> 
    </div>
    <div>
        <span>姓名{{personObj.name}}</span>
        <span>年龄{{personObj.age}}</span>
        <button @click="ageChange">age++</button>
    </div>
  </div>
</template>

<script setup>
import { watch,ref, computed} from "@vue/runtime-core";

let numAccount1=ref(10),numAccount2=ref(20);
let changeStr1=ref('无变化'),changeStr2=ref('无变化');
let strAmountDiff1=ref(0),strAmountDiff2=ref(0);
let personObj=ref({
    name:'zhangshan',age:'18'
})
function ageChange(){
    personObj.value.age++;
}
watch(
    ()=>personObj.value,
    (newNum,oldNum)=>{ console.log(newNum,oldNum);},
    {deep:true,immediate:true}
)
function changeNum(){
    numAccount1.value += parseFloat(strAmountDiff1.value);
    numAccount2.value += parseFloat(strAmountDiff2.value);
    strAmountDiff1.value=0;
    strAmountDiff2.value=0;
}
watch(
    ()=>numAccount1.value,//监控的变量
    (newNum,oldNum)=>{ changeStr1.value=oldNum+'变成'+newNum},
    // {deep:true,immediate:true}//监控复杂数据类型  深度访问和立即执行 初始化要执行一次
)
watch(
    ()=>numAccount2.value,//监控的变量
    (newNum,oldNum)=>{ changeStr2.value=oldNum+'变成'+newNum},
)
const totalNum= computed(()=>{
    return  numAccount1.value+numAccount2.value;
})
</script>

<style scoped>
span{
    margin: 10px;
}
.inner>div{
    margin:10px 0;
}
input{
    margin: 0 3px;
}
.inner>div:hover{
    background-color: #ddd;
}
</style>